﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SendCodeTest
{
    public partial class Form1 : Form
    {
        string[] lines = null, lines2 = null;
        bool bCOntinus = false, bCOntinus2 = false;
        Socket skt = null, skt2 = null;
        int iSend = 0, iSend2 = 0;
        bool bClose = true, bClose2 = true;
        byte[] recBuff = new byte[128];
        byte[] recBuff2 = new byte[128];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            txtCodePath.Text = Application.StartupPath + "\\code.txt";
            txtCodePath2.Text = Application.StartupPath + "\\code2.txt";

            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    txtIP.Text = ipa.ToString();
                }
            }
            
            if (File.Exists(txtCodePath.Text))
            {
                lines = File.ReadAllLines(txtCodePath.Text, Encoding.GetEncoding("GBK"));
                txtCodeQty.Text = lines.Length.ToString();

                if (lines.Length > 0)
                {
                    string[] items = lines[0].Split(new string[] { "，", "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (items.Length >= 5)
                    {
                        txtPZWH.Text = items[items.Length - 3];
                        int idx1 = 25;
                        int idx2 = lines[0].IndexOf(items[items.Length - 3]);
                        idx2--;

                        txtTYM.Text = lines[0].Substring(idx1, idx2 - idx1);
                    }
                }
            }

            if (File.Exists(txtCodePath2.Text))
            {
                lines2 = File.ReadAllLines(txtCodePath2.Text, Encoding.GetEncoding("GBK"));
                txtCodeQty2.Text = lines2.Length.ToString();
            }

            skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            skt2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            string CurrentScreenName = Screen.FromControl(this).DeviceName;
            Console.WriteLine("Screen: " + CurrentScreenName);

            lstOprCode.SelectedIndex = 0;


        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)文本文件|*.txt|(*.*)所有文件|*.*";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtCodePath.Text = ofd.FileName;

                if (File.Exists(txtCodePath.Text))
                {
                    lines = File.ReadAllLines(txtCodePath.Text, Encoding.GetEncoding("GBK"));
                    txtCodeQty.Text = lines.Length.ToString();
                    txtHasSend.Text = "0";

                    if (lines.Length>0)
	                {
                        string[] items = lines[0].Split(new string[]{"，", ","}, StringSplitOptions.RemoveEmptyEntries);
                        if (items.Length>=5)
                        {
                            txtPZWH.Text = items[items.Length-3];
                            int idx1 = 25;
                            int idx2 = lines[0].IndexOf(items[items.Length - 3]);
                            idx2--;

                            txtTYM.Text = lines[0].Substring(idx1, idx2 - idx1);
                        }
	                }
                    
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (chkUTF8.Checked)
            {
                txtCodePath.Text = Application.StartupPath + "\\code_utf8.txt";
            }
            else
            {
                txtCodePath.Text = Application.StartupPath + "\\code.txt";
            }

            if (File.Exists(txtCodePath.Text))
            {
                lines = File.ReadAllLines(txtCodePath.Text, Encoding.GetEncoding("GBK"));
                txtCodeQty.Text = lines.Length.ToString();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (lines == null || lines.Length <= iSend)
            {
                MessageBox.Show("无数据可发送");
            }

            if (button3.Text == "连续")
            {
                button3.Text = "停止";
                bCOntinus = true;
                timer1.Start();
            }
            else
            {
                button3.Text = "连续";
                bCOntinus = false;
                timer1.Stop();
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (bCOntinus)
            {
                int a = new Random().Next();

                if (a%20 == 1 && chkPick.Checked)
                {
                    SendPick();
                }
                else
                {
                    Send();
                }
                
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (button4.Text == "连接")
            {
                try
                {
                    IPAddress ip = IPAddress.Parse(txtIP.Text);

                    if (skt != null)
                    {
                        skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    }

                    skt.Connect(ip, Convert.ToInt32(txtPort.Text));
                    button4.Text = "断开";
                    bClose = false;
                    new Thread(new ParameterizedThreadStart(receiveFromSrv)).Start(skt);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                button4.Text = "连接";
                bClose = true;
                skt.Shutdown(SocketShutdown.Both);
            }

        }

        private void receiveFromSrv(object obj)
        {
            Socket skt = obj as Socket;
            int receivedBytesCount;

            while (!bClose)
            {
                try
                {

                    receivedBytesCount = skt.Receive(recBuff, 128, SocketFlags.None);//一直阻塞，直到有数据或者断开连接

                    //收到数据
                    //CallCtrlWithThreadSafety.AppendText(txtCode, Encoding.Default.GetString(recBuff, 0, recBuffLen), this);
                    CallCtrlWithThreadSafety.AppendText(txtRec, Encoding.UTF8.GetString(recBuff, 0, 128), this);
                }
                catch (SocketException e)
                {
                    //10035 == WSAEWOULDBLOCK  
                    if (e.NativeErrorCode.Equals(10035))
                    {
                        //仍然处于连接状态,但是发送可能被阻塞  
                    }
                    else
                    {
                        //连接错误,返回错误代码:e.NativeErrorCode  
                    }
                }
            }

            skt.Shutdown(SocketShutdown.Both);
        }

        private void receiveFromSrv2(object obj)
        {
            Socket skt = obj as Socket;
            int receivedBytesCount;

            while (!bClose2)
            {
                try
                {

                    receivedBytesCount = skt.Receive(recBuff2, 128, SocketFlags.None);//一直阻塞，直到有数据或者断开连接

                    //收到数据
                    //CallCtrlWithThreadSafety.AppendText(txtCode, Encoding.Default.GetString(recBuff, 0, recBuffLen), this);
                    CallCtrlWithThreadSafety.AppendText(txtRec2, Encoding.UTF8.GetString(recBuff2, 0, 128), this);
                }
                catch (SocketException e)
                {
                    //10035 == WSAEWOULDBLOCK  
                    if (e.NativeErrorCode.Equals(10035))
                    {
                        //仍然处于连接状态,但是发送可能被阻塞  
                    }
                    else
                    {
                        //连接错误,返回错误代码:e.NativeErrorCode  
                    }
                }
            }

            skt.Shutdown(SocketShutdown.Both);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (lines == null || lines.Length <= iSend)
            {
                MessageBox.Show("无数据可发送");
            }

            Send();
            
        }

        void Send(string strToSend = "")
        {
            string line = lines[iSend];
            byte[] toSend;

            if (!string.IsNullOrEmpty(strToSend))
            {
                line = strToSend;
            }

            if (!string.IsNullOrEmpty(txtTYM.Text) && !string.IsNullOrEmpty(txtPZWH.Text))
            {
                
                if (chkSN.Checked)
                {
                    line = line.Substring(0, 17);
                    line += iSend.ToString("D7");
                }
                else
	            {
                    line = line.Substring(0, 24);
	            }
                line += "，";
                line += txtTYM.Text;
                line += "，";
                line += txtPZWH.Text;
                line += "，";
                line += "山东硕创科技";
                line += "，";
                line += "8988888";
            }

            txtCode1.Text = line;

            if (!string.IsNullOrEmpty(txtSuffix.Text))
            {
                line = txtSuffix.Text + line;
            }

            if (chkCR.Checked)
            {
                line += "\r";
            }

            if (chkLF.Checked)
            {
                line += "\n";
            }

            if (chkUTF8.Checked)
            {
                toSend = Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, Encoding.GetEncoding("GBK").GetBytes(line));
            }
            else
            {
                toSend = Encoding.GetEncoding("GBK").GetBytes(line);
            }

            try
            {
                skt.Send(toSend);
                iSend++;
                txtHasSend.Text = iSend.ToString();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        void Send2(string strToSend = "")
        {
            string line = lines2[iSend];
            byte[] toSend;

            if (!string.IsNullOrEmpty(strToSend))
            {
                line = strToSend;
            }

            if (!string.IsNullOrEmpty(txtTYM.Text) && !string.IsNullOrEmpty(txtPZWH.Text))
            {

                if (chkSN2.Checked)
                {
                    line = line.Substring(0, 17);
                    line += iSend2.ToString("D7");
                }
                else
                {
                    line = line.Substring(0, 24);
                }
                line += "，";
                line += txtTYM.Text;
                line += "，";
                line += txtPZWH.Text;
                line += "，";
                line += "山东硕创科技";
                line += "，";
                line += "8988888";
            }

            if (!string.IsNullOrEmpty(txtSuffix2.Text))
            {
                line = txtSuffix2.Text + line;
            }

            if (chkCR2.Checked)
            {
                line += "\r";
            }

            if (chkLF2.Checked)
            {
                line += "\n";
            }

            if (chk2UTF8.Checked)
            {
                toSend = Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, Encoding.GetEncoding("GBK").GetBytes(line));
            }
            else
            {
                toSend = Encoding.GetEncoding("GBK").GetBytes(line);
            }

            try
            {
                skt2.Send(toSend);
                iSend2++;
                txtHasSend2.Text = iSend2.ToString();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }


        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (skt != null && skt.Connected)
            {
                bClose = true;
                skt.Shutdown(SocketShutdown.Both);
            }

            if (skt2 != null && skt2.Connected)
            {
                bClose2 = true;
                skt2.Shutdown(SocketShutdown.Both);
            }
        }

        private void btnOprCode_Click(object sender, EventArgs e)
        {
            string line = lstOprCode.Text.Split(new char[]{'='})[1];
            byte[] toSend;

            if (chkCR3.Checked)
            {
                line += "\r";
            }

            if (chkLF3.Checked)
            {
                line += "\n";
            }

            if (chk3UTF8.Checked)
            {
                toSend = Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, Encoding.GetEncoding("GBK").GetBytes(line));
            }
            else
            {
                toSend = Encoding.GetEncoding("GBK").GetBytes(line);
            }

            try
            {
                skt.Send(toSend);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCode1_Click(object sender, EventArgs e)
        {
            string line = txtCode1.Text;
            byte[] toSend;

            if (chkCR3.Checked)
            {
                line += "\r";
            }

            if (chkLF3.Checked)
            {
                line += "\n";
            }

            if (chk3UTF8.Checked)
            {
                toSend = Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, Encoding.GetEncoding("GBK").GetBytes(line));
            }
            else
            {
                toSend = Encoding.GetEncoding("GBK").GetBytes(line);
            }

            try
            {
                skt.Send(toSend);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCode2_Click(object sender, EventArgs e)
        {
            string line = txtCode2.Text;
            byte[] toSend;

            if (chkCR3.Checked)
            {
                line += "\r";
            }

            if (chkLF3.Checked)
            {
                line += "\n";
            }

            if (chk3UTF8.Checked)
            {
                toSend = Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, Encoding.GetEncoding("GBK").GetBytes(line));
            }
            else
            {
                toSend = Encoding.GetEncoding("GBK").GetBytes(line);
            }

            try
            {
                skt.Send(toSend);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {//重置
            if (File.Exists(txtCodePath.Text))
            {
                lines = File.ReadAllLines(txtCodePath.Text, Encoding.GetEncoding("GBK"));
                txtCodeQty.Text = lines.Length.ToString();
                txtHasSend.Text = "0";
                iSend = 0;

                if (lines.Length > 0)
                {
                    string[] items = lines[0].Split(new string[] { "，", "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (items.Length >= 5)
                    {
                        txtPZWH.Text = items[items.Length - 3];
                        int idx1 = 25;
                        int idx2 = lines[0].IndexOf(items[items.Length - 3]);
                        idx2--;

                        txtTYM.Text = lines[0].Substring(idx1, idx2 - idx1);
                    }
                }

            }
        }

        private void btnSelfSend_Click(object sender, EventArgs e)
        {
            string line = txtCode1.Text;
            byte[] toSend;

            if (!string.IsNullOrEmpty(txtSuffix.Text))
            {
                line = txtSuffix.Text + line;
            }

            if (chkCR.Checked)
            {
                line += "\r";
            }

            if (chkLF.Checked)
            {
                line += "\n";
            }

            if (chkUTF8.Checked)
            {
                toSend = Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, Encoding.GetEncoding("GBK").GetBytes(line));
            }
            else
            {
                toSend = Encoding.GetEncoding("GBK").GetBytes(line);
            }

            try
            {
                skt.Send(toSend);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtRec_DoubleClick(object sender, EventArgs e)
        {
            txtRec.Text = "";
        }

        private void btnPath2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(*.txt)文本文件|*.txt|(*.*)所有文件|*.*";

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtCodePath2.Text = ofd.FileName;

                if (File.Exists(txtCodePath2.Text))
                {
                    lines2 = File.ReadAllLines(txtCodePath.Text, Encoding.GetEncoding("GBK"));
                    txtCodeQty2.Text = lines2.Length.ToString();
                    txtHasSend2.Text = "0";

                }
            }
        }

        private void btnConn2_Click(object sender, EventArgs e)
        {
            if (btnConn2.Text == "连接")
            {
                try
                {
                    IPAddress ip = IPAddress.Parse(txtIP.Text);

                    if (skt2 != null)
                    {
                        skt2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    }

                    skt2.Connect(ip, Convert.ToInt32(txtPort2.Text));
                    btnConn2.Text = "断开";
                    bClose2 = false;
                    new Thread(new ParameterizedThreadStart(receiveFromSrv2)).Start(skt2);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                btnConn2.Text = "连接";
                bClose2 = true;
                skt2.Shutdown(SocketShutdown.Both);
            }
        }

        private void btnReset2_Click(object sender, EventArgs e)
        {
            if (File.Exists(txtCodePath2.Text))
            {
                lines2 = File.ReadAllLines(txtCodePath2.Text, Encoding.GetEncoding("GBK"));
                txtCodeQty2.Text = lines2.Length.ToString();
                txtHasSend2.Text = "0";
                iSend2 = 0;

            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (bCOntinus2)
            {
                
                int a = new Random().Next();

                if (a % 20 == 1 && chkPick.Checked)
                {
                    SendPick2();
                }
                else
                {
                    Send2();
                }
            }
        }

        private void btnReSend2_Click(object sender, EventArgs e)
        {

        }

        private void btnSendPick2_Click(object sender, EventArgs e)
        {
            SendPick2();
        }

        void SendPick2()
        {
            try
            {
                skt2.Send(Encoding.ASCII.GetBytes("^P\r\n"));
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }

        void SendPick()
        {
            try
            {
                skt.Send(Encoding.ASCII.GetBytes("^P\r\n"));
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        private void btnSelfSend2_Click(object sender, EventArgs e)
        {
            string line = txtCode1.Text;
            byte[] toSend;

            if (!string.IsNullOrEmpty(txtSuffix2.Text))
            {
                line = txtSuffix2.Text + line;
            }

            if (chkCR2.Checked)
            {
                line += "\r";
            }

            if (chkLF2.Checked)
            {
                line += "\n";
            }

            if (chk2UTF8.Checked)
            {
                toSend = Encoding.Convert(Encoding.GetEncoding("GBK"), Encoding.UTF8, Encoding.GetEncoding("GBK").GetBytes(line));
            }
            else
            {
                toSend = Encoding.GetEncoding("GBK").GetBytes(line);
            }

            try
            {
                skt2.Send(toSend);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtRec2_DoubleClick(object sender, EventArgs e)
        {
            txtRec2.Text = "";
        }

        private void btnContinuous2_Click(object sender, EventArgs e)
        {
            if (lines2 == null || lines2.Length <= iSend2)
            {
                MessageBox.Show("无数据可发送");
            }

            if (btnContinuous2.Text == "连续")
            {
                btnContinuous2.Text = "停止";
                bCOntinus2 = true;
                timer2.Start();
            }
            else
            {
                btnContinuous2.Text = "连续";
                bCOntinus2 = false;
                timer2.Stop();
            }
        }

        private void btnSingle2_Click(object sender, EventArgs e)
        {
            if (lines2 == null || lines2.Length <= iSend)
            {
                MessageBox.Show("无数据可发送");
            }

            Send2();
        }

        private void btnSendPick_Click(object sender, EventArgs e)
        {
            SendPick();
        }

        private void txtPort_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button4.PerformClick();
            }
        }

        private void btnReSend_Click(object sender, EventArgs e)
        {

        }
    }
}
